#include "module_buffer.h"
#include <stdio.h>	/* printf */
#include <string.h>	/* strcpy */

#define SEND_STRING1 "hello world"
#define SEND_STRING2 "my name is"
#define SEND_STRING3 "module buffer"

extern mod_context_t module1;
extern mod_context_t module2;
extern mod_context_t module3;

int main()
{
	qbuf_t *qbuf_send, *qbuf_recv, *qbuf;
	
	/* init */
	qbuf_groups_cfg();
	modbuf_pre_init();
	
	modbuf_init(&module1);
	modbuf_init(&module2);
	modbuf_init(&module3);
	
	/* 1. main --> module1 */
	qbuf_send = qbuf_alloc(QBUF_GROUP_DATBUF);
	if (!qbuf_send) {
		printf("qbuf_alloc error\n");
		return -1;
	}
	
	strcpy(qbuf_send->addr, SEND_STRING1);
	qbuf_send->len = sizeof(SEND_STRING1);
	printf("main --> module1[%d]: %s\n", qbuf_send->len, qbuf_send->addr);

	modbuf_push(&module1, MOD_GROUP_USER, qbuf_send);
	qbuf_recv = modbuf_pop(&module1, MOD_GROUP_USER);
	if (!qbuf_recv) {
		printf("modbuf_pop error\n");
		return -1;
	}
	printf("module1 <== got [%d]: %s\n\n\n", qbuf_recv->len, qbuf_recv->addr);
	qbuf_free(qbuf_recv);

	/* 2. main --> module1 --> module2 --> module3 --> module1 */
	qbuf = qbuf_alloc(QBUF_GROUP_MSGBUF);
	if (!qbuf) {
		printf("qbuf_alloc error\n");
		return -1;
	}

	////////
	strcpy(qbuf->addr, SEND_STRING1);
	qbuf->len = sizeof(SEND_STRING1);
	printf("main --> module1    [%d]: %s\n", qbuf->len, qbuf->addr);
	modbuf_push(&module1, MOD_GROUP_SYS, qbuf);

	qbuf = modbuf_pop(&module1, MOD_GROUP_SYS);
	if (!qbuf) {
		printf("modbuf_pop error\n");
		return -1;
	}
	printf("module1 <== got     [%d]: %s\n\n", qbuf->len, qbuf->addr);

	////////
	strcpy(qbuf->addr, SEND_STRING2);
	qbuf->len = sizeof(SEND_STRING2);
	printf("module1 --> module2 [%d]: %s\n", qbuf->len, qbuf->addr);
	modbuf_push(&module2, MOD_GROUP_SYS, qbuf);

	qbuf = modbuf_pop(&module2, MOD_GROUP_SYS);
	if (!qbuf) {
		printf("modbuf_pop error\n");
		return -1;
	}
	printf("module2 <== got     [%d]: %s\n\n", qbuf->len, qbuf->addr);

	////////
	strcpy(qbuf->addr, SEND_STRING3);
	qbuf->len = sizeof(SEND_STRING3);
	printf("module2 --> module3 [%d]: %s\n", qbuf->len, qbuf->addr);
	modbuf_push(&module3, MOD_GROUP_SYS, qbuf);

	qbuf = modbuf_pop(&module3, MOD_GROUP_SYS);
	if (!qbuf) {
		printf("modbuf_pop error\n");
		return -1;
	}
	printf("module3 <== got     [%d]: %s\n\n", qbuf->len, qbuf->addr);

	////////
	strcpy(qbuf->addr, SEND_STRING1);
	qbuf->len = sizeof(SEND_STRING1);
	printf("module3 --> module1 [%d]: %s\n", qbuf->len, qbuf->addr);
	modbuf_push(&module1, MOD_GROUP_SYS, qbuf);

	qbuf = modbuf_pop(&module1, MOD_GROUP_SYS);
	if (!qbuf) {
		printf("modbuf_pop error\n");
		return -1;
	}
	printf("module1 <== got     [%d]: %s\n\n", qbuf->len, qbuf->addr);

	qbuf_free(qbuf);

	/* exit */

	printf("test pass\n");

	modbuf_destroy(&module1);
	modbuf_destroy(&module2);
	modbuf_destroy(&module3);
	
	return 0;
}